<template>
  <div class="main-content">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchKeyword"
          placeholder="输入分类名称/负责人"
          clearable
          style="width: 300px"
          @clear="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="primary" @click="handleAdd">新增分类</el-button>
    </div>

    <!-- 分类表格 -->
    <el-table :data="paginatedData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center"/>
      <el-table-column prop="name" label="分类名称" width="180" align="center"/>
      <el-table-column prop="productCount" label="关联商品数" width="120" align="center"/>
      <el-table-column prop="manager" label="负责人" width="120" align="center"/>
      <el-table-column prop="updater" label="最后修改人" width="120" align="center"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="240" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="240" align="center"></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: #ff4d4f" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="filteredData.length"
        :page-sizes="[8, 12, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        class="pagination"
    />
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑分类' : '新增分类'"
        width="400px"
        @close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input
              v-model="form.name"
              placeholder="如：电子产品"
              clearable
              maxlength="20"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref, computed, onMounted, reactive, watch} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {addCategory, deleteCategory, deleteProduct, getAllCategoriesInfo, updateCategory} from "@/api/auth.js";

// 丰富模拟数据（共20条）
const rawData = ref([
  {
    id: 1,
    name: '数码3C',
    productCount: 54,
    manager: '张三',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 2,
    name: '家居生活',
    productCount: 491,
    manager: '李四',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 3,
    name: '服饰箱包',
    productCount: 127,
    manager: '王五',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 4,
    name: '食品生鲜',
    productCount: 44,
    manager: '张三',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 5,
    name: '家用电器',
    productCount: 368,
    manager: '赵六',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 6,
    name: '母婴用品',
    productCount: 89,
    manager: '陈七',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 7,
    name: '美妆个护',
    productCount: 256,
    manager: '林芳',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 8,
    name: '运动户外',
    productCount: 154,
    manager: '吴磊',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 9,
    name: '图书音像',
    productCount: 732,
    manager: '郑洁',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 10,
    name: '办公设备',
    productCount: 63,
    manager: '周涛',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 11,
    name: '汽车用品',
    productCount: 42,
    manager: '孙强',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 12,
    name: '宠物用品',
    productCount: 175,
    manager: '刘菲',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 13,
    name: '珠宝首饰',
    productCount: 28,
    manager: '黄薇',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 14,
    name: '家装建材',
    productCount: 93,
    manager: '徐明',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 15,
    name: '手机配件',
    productCount: 467,
    manager: '马龙',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 16,
    name: '智能设备',
    productCount: 309,
    manager: '韩雪',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 17,
    name: '游戏设备',
    productCount: 84,
    manager: '钱枫',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 18,
    name: '摄影器材',
    productCount: 57,
    manager: '杨阳',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 19,
    name: '乐器',
    productCount: 36,
    manager: '欧阳娜',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  },
  {
    id: 20,
    name: '工业设备',
    productCount: 12,
    manager: '秦刚',
    updater: '张三',
    createTime: '2025-01-01',
    updateTime: '2025-01-01'
  }
])

// 搜索和分页逻辑
const searchKeyword = ref('')
const pagination = ref({current: 1, size: 8})

// 过滤数据
const filteredData = computed(() => {
  return rawData.value.filter(item =>
      item.name.includes(searchKeyword.value) ||
      item.manager.includes(searchKeyword.value)
  )
})

// 分页数据
const paginatedData = computed(() => {
  const start = (pagination.value.current - 1) * pagination.value.size
  return filteredData.value.slice(start, start + pagination.value.size)
})
const initData = async () => {
  try {
    const res = await getAllCategoriesInfo()
    if (res.code === 200) {
      rawData.value = res.data
    } else {
      ElMessage.error(res.message)
    }

  } catch (e) {
    ElMessage.error(res.message)
  }

}
onMounted(() => {
  initData()


})

const handleSearch = () => pagination.value.current = 1
const handleAdd = () => {
  form.id = null
  form.name = null
  isEdit.value = false
  dialogVisible.value = true
  console.log(form)
}
const handleEdit = (row) => {
  form.name = row.name
  form.id = row.id
  isEdit.value = true
  dialogVisible.value = true
  console.log(row)
}
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除 ${row.name}？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await deleteCategory(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')

    } else {
      ElMessage.error(res.message)

    }
    await initData()
  } catch (e) {
       ElMessage.error('未知错误请联系管理员')

  }


}
const isEdit = ref(false)

// 表单数据
const form = reactive({id: '', name: ''})

// 规则
const rules = {
  name: [
    {required: true, message: '必填', trigger: 'blur'},
    {max: 20, message: '最多20字', trigger: 'blur'}
  ]
}


// 提交
const formRef = ref()
const dialogVisible = ref(false)
const submitForm = async () => {
  if (isEdit.value) {

    try {
      const res = await updateCategory(form)
       console.log('res')
      if (res.code === 200) {
        ElMessage.success('修改成功!')

        dialogVisible.value = false
        form.name = ''
        form.id = ''
      } else {
        ElMessage.error('111')
      }
    } catch (e) {
      ElMessage.error('111')
    }
    await initData()
  } else {
    try {
      const res = await addCategory(form.name)
      if (res.code === 200) {
        ElMessage.success('添加成功!')


      } else {
        ElMessage.error(e)
      }
      await initData()
      dialogVisible.value = false
      form.name = ''
      form.id = ''
    } catch (e) {
      ElMessage.error(e)
    }
  }
}

// 关闭处理
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.main-content {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-table {
  margin: 10px 0;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
}
</style>